package com.example.experiment4.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.example.experiment4.domain.Person;
import com.example.experiment4.utils.JudgmentInformation;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReadExcel {
    @Resource
    JudgmentInformation info;

    public List<Person> singleExcel(String filePath) {
        try {
            ExcelReader reader = ExcelUtil.getReader(FileUtil.file(filePath));
            List<List<Object>> readAll = reader.read();
            List<Person> plist = new ArrayList<>();
            for (List<Object> list : readAll) {
                Person p = new Person();
                for (Object obj : list) {
                    // 每一个obj就是每一个单元格
                    if (obj == null) {
                        break;
                    }
                    if (info.isName(obj.toString())) {
                        p.setName(obj.toString());
                    } else if (info.checkAddress(obj.toString())) {
                        p.setAddress(obj.toString());
                    } else if (info.isPhone(obj.toString())) {
                        p.setPhone(obj.toString());
                    }
                }
                if (!(p.getName() == null && p.getPhone() == null && p.getAddress() == null)) {
                    plist.add(p);
                }
            }
            return plist;
        } catch (Exception e) {
            System.out.println("读取文件异常！");
            return null;
        }
    }

    @Resource
    ReadFolder folder;

    public List<Person> underFolder(String pathname) {
        List<String> flist = folder.getFolderFileList(pathname);
        List<Person> plist = new ArrayList<>();
        if (flist.isEmpty()) {
            return null;
        }
        for (String path : flist) {
            if (singleExcel(path) != null){
                for (Person p : singleExcel(path)) {
                    if (!(p.getName() == null && p.getAddress() == null && p.getPhone() == null)) {
                        plist.add(p);
                    }
                }
            }
        }
        return plist;
    }
}
